package controller

import (
	"mime/multipart"
	"net/http"

	"github.com/kataras/iris"
	"github.com/kataras/iris/sessions"

	"im/common"
	"im/dao"
	"im/errcode"
	"im/model"
	"im/service"
)

type AttachmentsController struct {
	Session *sessions.Session
	Ctx     iris.Context
	Base
}

// swagger:route POST /attachments attachments post-attachments
//
// 创建attachments
//
// 将资源上传, 下次可以通过sha1来获取
//   Security:
//   - jwt_key:
//   Responses:
//     200: GetAttachmentBySha1
func (c *AttachmentsController) Post() {
	var (
		user = c.Ctx.Values().Get("user").(model.Users)
		file multipart.File
		info *multipart.FileHeader
		err  error
	)

	// Get the file from the request.
	file, info, err = c.Ctx.FormFile("file")
	if err != nil {
		c.SendCry(errcode.NewError(errcode.DefaultRequestCode))
		return
	}
	defer file.Close()
	path, err := service.NewAttachments().UploadToOss(user, file, info)
	if err != nil {
		c.SendCry(err)
		return
	}
	c.SendSmile(path)
}

// swagger:route GET /attachments/{sha1} attachments get-attachments-byid
//
// 获取资源信息
//
// 根据sha1来获取资源,一般是用不到
//   Security:
//   - jwt_key:
//   Responses:
//     200: EmptyResponse
func (c *AttachmentsController) GetBy(sha1 string) {
	var (
		user = c.Ctx.Values().Get("user").(model.Users)
		m    = &model.Attachments{}
	)

	m = dao.NewAttachmentsDao().GetFileBySha1(user.AppsId, sha1)

	if m == nil {
		c.Ctx.StatusCode(http.StatusNotFound)
		c.Ctx.JSON(common.SendSad("指定附件资源不存在你"))
		return
	}
	c.SendSmile(m)
}
